#!/bin/bash
#!/usr/bin/env bash
set -e

export MAIN_DYLIB="${1}"
export cj_frontend_path="${2}"
export cangjie_path="${3}"
export outputDir="${4}"
export is_simulator="${5}"

if [ ! -f "$MAIN_DYLIB" ]; then
    echo "Error: main dynamic library not exist: ${MAIN_DYLIB}"
    exit 1
fi

if [ ! -d "${cangjie_path}" ]; then
    echo "cj_frontend_path not exist: ${cj_frontend_path}"
    exit 1
fi

if [ ! -d "${cangjie_path}" ]; then
    echo "cangjie_path not exist: ${cangjie_path}"
    exit 1
fi

# create temp directory
TEMP_DIR=$(mktemp -d)
trap 'rm -rf "$TEMP_DIR"' EXIT

cp -R "$cj_frontend_path/ohos/"* "$TEMP_DIR"

if [ "$is_simulator" == "True" ]; then
    cp -R "$cangjie_path/runtime/lib/ios_simulator_aarch64_cjnative/"* "$TEMP_DIR"
else
    cp -R "$cangjie_path/runtime/lib/ios_aarch64_cjnative/"* "$TEMP_DIR"
fi

# get dependencies list
echo "Analyzing dependencies..."
ALL_DEPS=""

# level1：main dylib dependencies
LEVEL1=$(otool -L "$MAIN_DYLIB" | grep '@rpath' | awk '{print $1}' | sed 's/@rpath\///')
ALL_DEPS="$LEVEL1"
# level2
for dep in $LEVEL1; do
    dep_file=$(find "$TEMP_DIR" -name "$dep" -type f 2>/dev/null | head -1)
    if [ -f "$dep_file" ]; then
        LEVEL2=$(otool -L "$dep_file" | grep '@rpath' | awk '{print $1}' | sed 's/@rpath\///')
        ALL_DEPS="$ALL_DEPS $LEVEL2"
    fi
done

UNIQUE_DEPS=$(echo "$ALL_DEPS" | tr ' ' '\n' | sort -u | grep -v '^$')
if [ -z "$UNIQUE_DEPS" ]; then
    echo "No dependencies found."
    exit 0
fi

cp "$TEMP_DIR/libohos.web.net_error_list.dylib" "$outputDir/"

for dep in $UNIQUE_DEPS; do
    found_files=$(find "$TEMP_DIR" -name "$dep" -type f 2>/dev/null)
    if [ -n "$found_files" ]; then
        for file in $found_files; do
            if [ -f "$file" ]; then
                cp "$file" "$outputDir/"
                if [ $? -eq 0 ]; then
                    echo "copy success: $(basename "$file") -> $outputDir"
                else
                    echo "copy faild: $file"
                fi
            fi
        done
    else
        echo "not find: $dep"
    fi
done
